﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;

namespace FingerTip.Infrastructure.Environment
{
    public class Kernel
    {
        private static string _environment;

        static Kernel()
        {
            SetProperties();
            Validate();
        }

        
        private static void SetProperties()
        {
            IDictionary environmentVariables = System.Environment.GetEnvironmentVariables();
            _environment = (string)environmentVariables["ASPNETCORE_ENVIRONMENT"];
        }

        private static void Validate()
        {
           
            if (string.IsNullOrWhiteSpace(_environment))
            {
                _environment = DeployEnvironment.Test.ToString().ToLowerInvariant();
            }
            else
            {
                string text2 = Kernel.FormalizeEnvironment(_environment);
                if (text2 == null || text2 != _environment.ToLowerInvariant())
                {
                    throw new ArgumentOutOfRangeException("ASPNETCORE_ENVIRONMENT", _environment);
                }
                _environment = text2;
            }
            
        }

        public static bool IsBaseEnvironment(string environment)
        {
            return Kernel.FormalizeEnvironment(environment) == environment;
        }

        private static string FormalizeEnvironment(string env)
        {
            if (string.IsNullOrWhiteSpace(env))
            {
                return null;
            }
            var names = Enum.GetNames(typeof(DeployEnvironment));
            return (from text in names where env.StartsWith(text, StringComparison.OrdinalIgnoreCase) select text.ToLowerInvariant()).FirstOrDefault();
        }


        /// <summary>
        /// 部署环境类别(取值固定为test/qa/uat/stage/product)
        /// </summary>
        public static string Environment => _environment;
    }
}
